From 5b01849cc42cb410fc4ce152519a27fb93d9bcb6 Mon Sep 17 00:00:00 2001 From: =?utf8?q?David=20H=C3=A4rdeman?= Date: Fri, 28 Nov 2025 11:35:49 +0100 Subject: [PATCH] statefiles: add a dirfd helper function MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit The same logic was repeated three times in config.c, move it to a single function in statefiles.c. Signed-off-by: David Härdeman Link: https://github.com/openwrt/odhcpd/pull/333 Signed-off-by: Álvaro Fernández Rojas --- src/config.c | 34 ++++++---------------------------- src/statefiles.c | 20 ++++++++++++++++++++ src/statefiles.h | 2 ++ 3 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/config.c b/src/config.c index 0e588b6..97af99a 100644 --- a/src/config.c +++ b/src/config.c @@ -23,6 +23,7 @@ #include "router.h" #include "dhcpv6-pxe.h" #include "dhcpv4.h" +#include "statefiles.h" static struct blob_buf b; @@ -2388,35 +2389,12 @@ void odhcpd_reload(void) char *file = basename(config.dhcp_statefile); memmove(config.dhcp_statefile, file, strlen(file) + 1); - mkdir_p(dir, 0755); - - close(config.dhcp_statedir_fd); - config.dhcp_statedir_fd = open(dir, O_PATH | O_DIRECTORY | O_CLOEXEC); - if (config.dhcp_statedir_fd < 0) - error("Unable to open statedir: '%s': %m", dir); - } - - if (config.dhcp_hostsdir) { - char *dir = strdupa(config.dhcp_hostsdir); - - mkdir_p(dir, 0755); - - close(config.dhcp_hostsdir_fd); - config.dhcp_hostsdir_fd = open(dir, O_PATH | O_DIRECTORY | O_CLOEXEC); - if (config.dhcp_hostsdir_fd < 0) - error("Unable to open hostsdir '%s': %m", dir); - } - - if (config.ra_piofolder) { - char *path = strdupa(config.ra_piofolder); - - mkdir_p(path, 0755); - - close(config.ra_piofolder_fd); - config.ra_piofolder_fd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC); - if (config.ra_piofolder_fd < 0) - error("Unable to open piofolder '%s': %m", path); + statefiles_setup_dirfd(dir, &config.dhcp_statedir_fd); + } else { + statefiles_setup_dirfd(NULL, &config.dhcp_statedir_fd); } + statefiles_setup_dirfd(config.dhcp_hostsdir, &config.dhcp_hostsdir_fd); + statefiles_setup_dirfd(config.ra_piofolder, &config.ra_piofolder_fd); vlist_flush(&lease_cfgs); diff --git a/src/statefiles.c b/src/statefiles.c index da31ca6..21201cb 100644 --- a/src/statefiles.c +++ b/src/statefiles.c @@ -338,3 +338,23 @@ bool statefiles_write() return true; } + +void statefiles_setup_dirfd(const char *path, int *dirfd) +{ + if (!dirfd) + return; + + if (*dirfd >= 0) { + close(*dirfd); + *dirfd = -1; + } + + if (!path) + return; + + mkdir_p(strdupa(path), 0755); + + *dirfd = open(path, O_PATH | O_DIRECTORY | O_CLOEXEC); + if (*dirfd < 0) + error("Unable to open directory '%s': %m", path); +} diff --git a/src/statefiles.h b/src/statefiles.h index 80be746..de71397 100644 --- a/src/statefiles.h +++ b/src/statefiles.h @@ -12,4 +12,6 @@ bool statefiles_write(void); +void statefiles_setup_dirfd(const char *path, int *dirfdp); + #endif /* _STATEFILES_H_ */ -- 2.30.2